#include "devinsight.h"


/* 二进制打印8个bit，buffer长度10. */
const char* bx8b(void* ptr, char* buffer)
{
    if (buffer == NULL) {
        buffer = (char*)palloc0(sizeof(char) * 10);
    }
    uint8 num = *(uint8*)ptr;
    buffer[0] = ((num >> 7) & 1) + '0';
    buffer[1] = ((num >> 6) & 1) + '0';
    buffer[2] = ((num >> 5) & 1) + '0';
    buffer[3] = ((num >> 4) & 1) + '0';
    buffer[4] = ' ';
    buffer[5] = ((num >> 3) & 1) + '0';
    buffer[6] = ((num >> 2) & 1) + '0';
    buffer[7] = ((num >> 1) & 1) + '0';
    buffer[8] = ((num >> 0) & 1) + '0';
    buffer[9] = '\0';
    return buffer;
}


/* 二进制打印16个bit，buffer长度20. */
const char* bx16b(void* ptr, char* buffer)
{
    if (buffer == NULL) {
        buffer = (char*)palloc(sizeof(char) * 20);
    }
    
    uint16 num = *(uint16*)ptr;
    char* pbuf = buffer;
    
    for (int i = 1; i >= 0; i--, pbuf += 10) {
        uint8 partnum = (uint8)((num >> 8 * i) & 0xff);
        bx8b(&partnum, pbuf);
        pbuf[9] = ' ';
    }
    buffer[19] = '\0';
    
    return buffer;
}


/* 二进制打印32个bit，buffer长度40. */
const char* bx32b(void* ptr, char* buffer)
{
    if (buffer == NULL) {
        buffer = (char*)palloc(sizeof(char) * 40);
    }
    
    uint32 num = *(uint32*)ptr;
    char* pbuf = buffer;
    
    for (int i = 3; i >= 0; i--, pbuf += 10) {
        uint8 partnum = (uint8)((num >> 8 * i) & 0xff);
        bx8b(&partnum, pbuf);
        pbuf[9] = ' ';
    }
    buffer[39] = '\0';
    return buffer;
}


/* 二进制打印64个bit，buffer长度80. */
const char* bx64b(void* ptr, char* buffer)
{
    if (buffer == NULL) {
        buffer = (char*)palloc(sizeof(char) * 80);
    }
    
    uint64 num = *(uint64*)ptr;
    char* pbuf = buffer;
    
    for (int i = 7; i >= 0; i--, pbuf += 10) {
        uint8 partnum = (uint8)((num >> 8 * i) & 0xff);
        bx8b(&partnum, pbuf);
        pbuf[9] = ' ';
    }
    buffer[79] = '\0';
    return buffer;
}



